class MyPageHeader extends BaseEditMaster {
    constructor(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
            returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl) {
        super(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
                returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl);
        this.hasFilterValue = true;
        this.taxRate = 0;
    }
    GetFilterValue() {
        let item = {};
        item['HeaderId'] = parseInt(this.dataId);
        item['CurrentUserId'] = parseInt($("#UserId").val());
        item['WorkFlowId'] = $("#WorkFlowId").val() === '' ? 0 : parseInt($("#WorkFlowId").val());

        return item;
    }
    // 得到非材料花费数据
    GetEntityData() {
        let item = {};
        item['headerId'] = $("#HeaderId").val();
        item['supplierId'] = $.trim($("#SupplierId").val());            //         
        item['supplierName'] = $.trim($("#SupplierName").val());        // 
        item['yearOfBill'] = $.trim($("#YearOfBill").val());            // 年
        item['monthOfBill'] = $.trim($("#MonthOfBill").val());          // 月
        item['destination'] = $.trim($("#Destination").val());          // 目的地
        item['description'] = formatNullInputValue($.trim($("#Description").val()));      // 备注
        item['createdBy'] = $.trim($("#UserId").val());
        item['updatedBy'] = $.trim($("#UserId").val());
        return JSON.stringify(item);
    }
    FillData(data) {
        let item = data.HeaderEntity;
        $("#HeaderId").val(item.headerId);
        $("#SupplierId").val(item.supplierId);
        $("#SupplierName").val(item.supplierName);
        $("#YearOfBill").val(item.yearOfBill);
        $("#MonthOfBill").val(item.monthOfBill);
        $("#UpdatedByName").val(item.updatedByName);
        $("#UpdatedDate").val(formatNullData(item.updatedDate));
        $("#Description").val(item.description);
        // 最后的审核人、审核日期
        $("#CheckedBy").val(item.checkedBy);
        $("#CheckedByName").val(item.checkedByName);
        $("#CheckedDate").val(item.checkedDate === null ? '' : item.checkedDate);
        $("#CheckedStatus").val(item.checkedStatus);
        $('#FlowOrderNo').val(item.flowOrderNo);

        // 设置用于控制的用户ID
        this.privateUserId = item.updatedBy;

        // 显示明细数据
        _InstancePageLines.BuildDataTable(data.LinesList);

        this.currentTaskPrivileges = item.currentTaskPrivileges;
        this.nextTaskPrivileges = item.nextTaskPrivileges;
        this.unCheckFlag = item.unCheckFlag;
        this.SetPageElementStatus(this.HidePageElement, this.ShowPageElement, function () {
            _InstancePageLines.AutoAdjustTableHeightForLines();
        });
        $("#SupplierName").focus();

        this.FetchCurrenctTaxRate();
    }
    Save() {
        super.Save(function (data, _this) {
            if (data > 0) {
                if (parseInt(_this.pageStatus) === 1) {
                    $("#HeaderId").val(data);   // 设置刚才插入的记录ID
                    $("#Action").val(2);
                    _this.dataId = data;
                    _this.pageStatus = 2;
                    $("#panelSlave").show();
                    $("#ButPrint").show();
                    $("#CheckedTip").removeClass().addClass("n2");
                    $("#CheckedTip").html("状态：未审核。");
                    $("#CheckedTip").show();
                }
            }
        });
    }
    New() {
        super.New();

        $('#tabData11 tbody').empty();
        $("#panelSlave").hide();
        this.rows = 0;
        // 自适应高度
        _InstancePageLines.AutoAdjustTableHeightForLines();

        // 设置初始默认值
        let _currentDate = new Date();
        $("#YearOfBill").val(_currentDate.getFullYear());
        $("#MonthOfBill").val(_currentDate.getMonth() + 1);
        $("#UpdatedByName").val($("#UserName").val());
        $("#UpdatedDate").val(getCurrentDate());
        $("#SupplierName").focus();

        this.FetchCurrenctTaxRate();
    }
    // 设置当前税率
    FetchCurrenctTaxRate() {
        super.DoAjax({}, "/master/tax_rate/fetchCurrentTaxRate.html", function (data, _this) {
            if (data !== null) {
                _this.taxRate = data.taxRate;
            } else {
                ShowErrorMessagePanel('当前税率获取失败。');
            }
        });
    }
    DoChoiceSupplier() {
        let _choice = new CommonChoice();
        let params = {};
        params['Flag'] = 0;
        params['CurrentUserId'] = null;
        params['NotInGroupId'] = null;
        _choice.DoChoiceSupplier(params, '选择供应商', (data) => {
            if (data) {
                // 判断是否数据发生了改变如果改变则设置改变标记
                if ($("#SupplierName").val() !== data[1]) {
                    $("#form_data").data("changed", true);
                }
                $("#SupplierId").val(data[0]);
                $("#SupplierName").val(data[1]);
            }
        });
    }
    ShowPageElement() {
        $("Button.act__save").show();
        if (!$("span.act__delete").hasClass("act__delete")) {
            $("span.act__delete").addClass("trash");
            $("span.act__delete i").addClass("fa-all fa-trash-o fa-1");
        }
    }
    HidePageElement() {
        //$("Button.act__save").hide();
        //$("span.act__delete").removeClass("trash");
        //$("span.act__delete i").removeClass("fa-all fa-trash-o fa-1");
    }
    Expand() {
        super.Expand(function () {
            // 自适应高度
            _InstancePageLines.AutoAdjustTableHeightForLines();
        });
    }
    /* 折叠 */
    Collapse() {
        super.Collapse(function () {
            // 自适应高度
            _InstancePageLines.AutoAdjustTableHeightForLines();
        });
    }
}

//------------------------------------------------------------------------------
// 明细处理部分
//------------------------------------------------------------------------------
class MyPageLines extends BaseEditSlave {
    constructor() {
        super('', '', '');
        this.$input = null;
    }
    BuildDataTable(result) {
        $('#tabData11 tbody').empty();
        // 得到数据列表
        if (result === null || result.length === 0) {
            $("#panelSlave").show();
            this.rows = 0;
            // 自适应高度
            _InstancePageLines.AutoAdjustTableHeightForLines();
            return false;
        }
        let content_01 = '';
        this.rows = result.length;
        for (let i = 0; i < result.length; i++) {
            content_01 += '<tr _mash_id="' + result[i].linesId + '">';
            content_01 += '<td style="text-align:center;">' + (i + 1) + '</td>';
            content_01 += '<td class="column__action"><span title="删除" class="trash act__delete" onclick="_InstancePageLines.DeleteLines($(this));"><i class="fa-all fa-trash-o fa-1"></i></span></td>';
            content_01 += '<td class="edited-cell">' + formatNullData(result[i].styleNo) + '</td>';
            content_01 += '<td class="edited-cell">' + formatNullData(result[i].cause) + '</td>';
            content_01 += '<td class="edited-cell" style="text-align:right;">' + result[i].costAmount + '</td>';
            content_01 += '<td class="edited-cell">' + formatNullData(result[i].invoiceNo) + '</td>';
            content_01 += '<td class="edited-cell" style="text-align:right;">' + formatNullData(result[i].taxRate) + '</td>';
            content_01 += '<td class="edited-cell">' + formatNullData(result[i].invoiceDate) + '</td>';
            content_01 += '<td class="edited-cell" _poId="' + result[i].poId + '">' + formatNullData(result[i].poNo) + '</td>';
            content_01 += '</tr>';
            $('#tabData11 tbody').append(content_01);
            content_01 = '';
        }
        // 设置明细部分高度
        this.AutoAdjustTableHeightForLines();

        let _cellid = "_cell__field";
        let _cellname = "__cell__field";
        let _this = this;
        $('#tabData11 tbody tr').find("td.edited-cell").click(function () {
            switch ($(this).index()) {
                case 7:
                    OnCellDateEditEvent($(this), _cellid, _cellname, "yyyy、MM");
                    break;
                case 8:
                    OnCellPopupEditEvent($(this), _cellid, _cellname, ($input) => {
                        _this.DoChoicePoNo($input);
                    });
                    break;
                case 2:
                    OnCellPopupEditEvent($(this), _cellid, _cellname, ($input) => {
                        _this.DoChoiceStyleNo($input);
                    });
                    break;
                default:
                    OnCellClickEvent($(this), _cellid, _cellname, 0);
                    break;
            }
        });

        setOneTableRowColor("tabData11");
        $("#panelSlave").show();
    }
    GetLinesData() {
        let _result = {};
        let jsonUpdate = [];
        let jsonInsert = [];
        $('#tabData11 tbody').find("tr").each(function () {
            if ($(this).find('td.dirty').length > 0) {
                let $row = $(this);
                let item = {};
                item['headerId'] = $("#HeaderId").val();
                item['linesId'] = $row.attr("_mash_id");
                item['styleNo'] = $.trim($row.find('td').eq(2).text());
                item['cause'] = formatNullInputValue($.trim($row.find('td').eq(3).text()));
                item['costAmount'] = $.trim($row.find('td').eq(4).text());
                item['invoiceNo'] = $.trim($row.find('td').eq(5).text());
                item['taxRate'] = $.trim($row.find('td').eq(6).text());      //税率
                //let _invoiceDate = null;
                //if ($.trim($row.find('td').eq(7).text()) !== '') {
                //    let _tmpArr = $.trim($row.find('td').eq(7).text()).split("、");
                //    _invoiceDate = _tmpArr[0] + '-' + _tmpArr[1] + '-01';
                //}
                item['invoiceDate'] = $.trim($row.find('td').eq(7).text()); //_invoiceDate; // 开票日
                item['poId'] = $.trim($row.find('td').eq(8).attr("_poId"));
                item['updatedBy'] = $("#UserId").val();
                item['createdBy'] = $("#UserId").val();
                if ($row.attr("_mash_id") === "0") {
                    jsonInsert.push(item);
                } else {
                    jsonUpdate.push(item);
                }

            }
        });
        _result['InsertList'] = jsonInsert;
        _result['UpdateList'] = jsonUpdate;
        _result['HeaderId'] = parseInt($("#HeaderId").val());

        return JSON.stringify(_result);
    }
    SaveLines() {
        //step 1、进行页面验证，失败则返回
        let _success = CheckGridInput01();
        if (!_success)
            return;

        super.SaveLines("/purchase/non_material_cost/lines/save.html", function (data, $self) {
            // 刷新明细
            $self.BuildDataTable(data.LinesList);
            ShowSuccessMessagePanel("保存成功。");
        });
    }
    // 添加新行以及新行的操作方式
    NewLines() {
        let $newLine = $('<tr class="newLine" _mash_id="0">' +
                '    <td style="height:25px;"></td>' +
                '    <td class="column__action"><span title="删除" class="trash act__delete" onclick="_InstancePageLines.RemoveNewLine($(this));"><i class="fa-all fa-trash-o fa-1"></i></span></td>' +
                '    <td class="edited-cell"></td>' +
                '    <td class="edited-cell"></td>' +
                '    <td class="edited-cell" style="text-align:right;"></td>' +
                '    <td class="edited-cell"></td>' +
                '    <td class="edited-cell" style="text-align:right;">' + _InstancePageHeader.taxRate + '</td>' +
                '    <td class="edited-cell"></td>' +
                '    <td class="edited-cell" _poId=""></td>' +
                '</tr>');
        $('#tabData11 tbody').prepend($newLine);   // 加在后面
        setOneTableRowColor("tabData11");
        this.rows = this.rows + 1;
        // 设置明细部分高度
        this.AutoAdjustTableHeightForLines();

        let _cellid = "_cell__field";
        let _cellname = "__cell__field";
        let _this = this;
        $('#tabData11 tbody tr').find("td.edited-cell").click(function () {
            switch ($(this).index()) {
                case 7:
                    OnCellDateEditEvent($(this), _cellid, _cellname, "yyyy、MM");
                    break;
                case 8:
                    OnCellPopupEditEvent($(this), _cellid, _cellname, ($input) => {
                        _this.DoChoicePoNo($input);
                    });
                    break;
                case 2:
                    OnCellPopupEditEvent($(this), _cellid, _cellname, ($input) => {
                        _this.DoChoiceStyleNo($input);
                    });
                    break;
                default:
                    OnCellClickEvent($(this), _cellid, _cellname, 0);
                    break;
            }
        });
    }
    RemoveNewLine($self) {
        showModal(350, 140, '删除确认', '', null, null, 1, '请问，确定要删除当前行吗？', () => {
            $self.parent().parent().remove();
            setOneTableRowColor("tabData11");

            this.rows = this.rows - 1;
            // 设置明细部分高度
            this.AutoAdjustTableHeightForLines();
        });
    }
    DeleteLines($self) {
        let params = {};
        params['HeaderId'] = $("#HeaderId").val();
        params['LinesId'] = $self.parent().parent().attr("_mash_id");
        params['DeletedBy'] = $.trim($("#UserId").val());
        super.DeleteLines(params, "/purchase/non_material_cost/lines/delete.html", function (data, _this) {
            if (data !== undefined) {
                // 刷新合同明细
                _this.BuildDataTable(data.LinesList);
            }

            ShowSuccessMessagePanel("删除成功。");
        });
    }
    // 选择订单合同号
    DoChoicePoNo($input) {
        this.$input = $input;
        let _choice = new CommonChoice();
        _choice.DoChoicePo(0, '选择订单', (data) => {
            if (data === false) {
                this.$input.focus();
            } else {
                this.$input.parent().attr("_poId", data[0]);
                this.$input.val(data[2]);
                this.$input.focus();
            }
        });
    }
    // 选择款号
    DoChoiceStyleNo($input) {
        this.$input = $input;
        let _choice = new CommonChoice();
        _choice.DoChoiceProduct(0, '选择款号', (data) => {
            if (data === false) {
                this.$input.focus();
            } else {
                this.$input.val(data[3]); // 实际上这里选择的是系列号
                this.$input.focus();
            }
        });
    }
    AutoAdjustTableHeightForLines() {
        let h = $(window).height();
        let _tabTop = 0;   // 用于随着窗口变化，下面明细高度随之变化的一个节点
        if ($("#panel_slave_butbar_01").css('display') === 'none') {
            _tabTop = $("#panelSlave").offset().top + 71;
        } else {
            _tabTop = $("#panelSlave").offset().top + 96;
        }
        let _rc = Math.floor((h - _tabTop - 10) / 25);
        let _dh = _rc * 25;
        let _rowH = this.rows * 25; // 计算行高
        _dh = (_rowH >= _dh) ? _dh : _rowH;

        $("#divD11").css({"max-height": _dh, height: _dh});
    }
}

var _InstancePageHeader = null;
var _InstancePageLines = null;

//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    let _pageStatus = parseInt($("#Action").val());
    let _dataId = $("#HeaderId").val();

    let non_material_cost_list_result = $.cookie("non_material_cost_list_result") === undefined ? "" : $.cookie("non_material_cost_list_result");
    let _pageListData = [];
    if (non_material_cost_list_result !== "") {
        _pageListData = non_material_cost_list_result.split(',');
        $("#rec_total_rows").text(_pageListData.length);
        $("#rec_cur_row").text($.inArray(_dataId, _pageListData) + 1);

        if (_pageListData.length > 0) {
            let index = $.inArray(_dataId, _pageListData);
            if (index === 0) {
                $("#ButPrev").attr("disabled", "disabled");
            } else {
                $("#ButNext").removeAttr("disabled");
            }
            if (index === (_pageListData.length - 1)) {
                $("#ButNext").attr("disabled", "disabled");
            } else {
                $("#ButPrev").removeAttr("disabled");
            }
        }
    } else {
        $("#rec_total_rows").text("1");
        $("#rec_cur_row").text("1");
    }

    _InstancePageHeader = new MyPageHeader(_dataId, 0, 0, _pageStatus, _pageListData,
            "/purchase/non_material_cost/list.html",
            "/purchase/non_material_cost/header/fetchByKey.html",
            "/purchase/non_material_cost/header/save.html",
            "/purchase/non_material_cost/header/export.html",
            "/purchase/non_material_cost/header/print.html");

    _InstancePageLines = new MyPageLines();

    $("#tabPanelHeader").wxTabs({tabContent: "tabPanelData"});

    $("#hPanelSplitter").click(function () {
        if ($(this).children("i").hasClass("fa-angle-double-up")) {
            _InstancePageHeader.Collapse();
        } else {
            _InstancePageHeader.Expand();
        }
    });

    _InstancePageHeader.OnPageLoad();
}

// 画面大小或者位置移动
function onPageResize() {
    if (_InstancePageLines !== null)
        _InstancePageLines.AutoAdjustTableHeightForLines();
}

//-----------------------------------------------------------------------------
// 验证函数
//-----------------------------------------------------------------------------
$.validator.setDefaults({
    ignore: 'hidden, [reaonly=readonly]'
});
$(function () {
    $("#form_data").validate({
        // Step 1：设置验证规则和错误消息
        rules: {
            _BillNo: "required",
            _DateOfDelivery: {
                dateISO: true,
                required: true
            },
            _CustomerName: "required",
            _ResponsibleByName: "required",
            _Destination: "required",
            _ShippingTypeName: "required"
        },
        messages: {
            _BillNo: "请填写非材料花费号。",
            _DateOfDelivery: {
                dateISO: "请填写正确的日期。",
                required: "请填写发货日期。"
            },
            _CustomerName: "请填写客户。",
            _ResponsibleByName: "请填写负责人。",
            _Destination: "请填写目的港。",
            _ShippingTypeName: "请填写运输方式。"
        },
        // Step 2：设置验证触发事件
        onclick: false,
        onfocusout: false,
        onfocusin: false,
        onkeyup: false,
        onkeydown: false,
        focusInvalid: false,
        // Step 3：设置错误信息提示
        showErrors: window.showErrors  //使用自定义的错误显示方法
    });
});

// 验证输入
function CheckGridInput01() {
    $('#tabData11 tbody').find("tr").each(function () {
        let _styleNo = $.trim($(this).find('td').eq(2).text()).length;
        let _cause = $.trim($(this).find('td').eq(3).text()).length;
        let _costAmount = $.trim($(this).find('td').eq(4).text()).length > 0 ? $.trim($(this).find('td').eq(4).text()) : 0; //
        if (_styleNo === 0) {
            GridCheckErrHandle($(this), 2, '款号不能空。');
        } else {
            GridCheckSuccessHandle($(this), 2);
        }
        if (_cause === 0) {
            GridCheckErrHandle($(this), 3, '花费原因不能空。');
        } else {
            GridCheckSuccessHandle($(this), 3);
        }
        if (_costAmount !== 0) {
            if (!isNumber(_costAmount)) {
                GridCheckErrHandle($(this), 4, '请输入正确的数字。');
            } else {
                GridCheckSuccessHandle($(this), 4);
            }
        } else {
            GridCheckErrHandle($(this), 4, '请输入正确的数字。');
        }
    });
    if ($('#tabData11 tbody').find('td.error').length > 0) {
        ShowErrorMessagePanel('对不起，填写的数据有错误。');
        return false;
    } else {
        return true;
    }
}

function GridCheckErrHandle($row, index, errMsg) {
    $row.find('td').eq(index).addClass("error");
    $row.find('td').eq(index).attr('title', errMsg);
}
function GridCheckSuccessHandle($row, index) {
    $row.find('td').eq(index).removeClass("error");
    $row.find('td').eq(index).attr('title', '');
}